<?php

class SensorsController extends RController
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
    public $defaultAction = 'admin';
	public $layout='//layouts/lay_column2';
    public $menu=array();
    public $moduleName="设备管理";	//此处修改本模块名称
    
    public function init()
	{
    	$leftmenu = 'yunying';	//此处修改模块所属菜单
		$this->menu = Yii::app()->params[$leftmenu];
	}

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'rights', // perform access control for CRUD operations
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('index','view'),
				'users'=>array('*'),
			),
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('create','update','command', 'results'),
				'users'=>array('@'),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('admin','delete'),
				'users'=>array('admin'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		$this->render('view',array(
			'model'=>$this->loadModel($id),
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$model=new Sensors;

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Sensors']))
		{
			$model->attributes=$_POST['Sensors'];
			$model->GROUPNAME_V = $_POST['BtBatterys']['RECORD_ID'];
			$model->BASENAME_V = $_POST['MtsysBase']['BASE_ID'];			
			
			if($model->save())
				$this->redirect(array('view','id'=>$model->RECORD_ID));
		}

//		$bases = MtsysBase::model()->findAll();
//		$batterys = BtBatterys::model()->findAll();
		
		$mUser=User::model()->findByPk(Yii::app()->user->id);
		$unit_level = $mUser->unit_level;	
		$unit_id = $mUser->unit_id;	

		switch ($mUser->unit_level){
			case 4:
				$bases = MtsysBase::model()->findAll(array(
														   'condition' => 'BASE_ID = :unit_id',
														   'params' => array(':unit_id' => $unit_id),
													));
				$sql = "SELECT c.GROUPNAME_V FROM mtsys_base a
				JOIN tbl_users b ON a.BASE_ID = b.unit_id
				JOIN bt_batterys c ON c.BASE_N = a.BASE_ID
				WHERE b.id = :uid";
				$batterys =  Yii::app()->db->createCommand($sql)->query(array(':uid' => Yii::app()->user->id));
				break;
			case 3:
				$bases = MtsysBase::model()->findAll(array(
						'condition' => 'COUNTY_ID = :unit_id',
						'params' => array(':unit_id' => $unit_id),
				));
				$sql = "SELECT c.GROUPNAME_V FROM mtsys_base a
				JOIN tbl_users b ON a.COUNTY_ID = b.unit_id
				JOIN bt_batterys c ON c.BASE_N = a.BASE_ID
				WHERE b.id = :uid";
				$batterys =  Yii::app()->db->createCommand($sql)->query(array(':uid' => Yii::app()->user->id));
				
				break;
			case 2:
				$bases = MtsysBase::model()->findAll(array(
						'condition' => 'CITY_ID = :unit_id',
						'params' => array(':unit_id' => $unit_id),
				));
				$sql = "SELECT c.GROUPNAME_V FROM mtsys_base a
				JOIN tbl_users b ON a.CITY_ID = b.unit_id
				JOIN bt_batterys c ON c.BASE_N = a.BASE_ID
				WHERE b.id = :uid";
				$batterys =  Yii::app()->db->createCommand($sql)->query(array(':uid' => Yii::app()->user->id));
				
				break;
			case 1:
/*				$sql = "select a.* from mtsys_base a 
						JOIN tbl_users b ON a.PROVINCE_ID = b.unit_id
						where b.id = :uid";
				$bases =  Yii::app()->db->createCommand($sql)->query(array(':uid' => Yii::app()->user->id));
*/				$bases = MtsysBase::model()->findAll(array(
						'condition' => 'PROVINCE_ID = :unit_id',
						'params' => array(':unit_id' => $unit_id),
				));
				$sql = "SELECT c.* FROM mtsys_base a
				JOIN tbl_users b ON a.PROVINCE_ID = b.unit_id
				JOIN bt_batterys c ON c.BASE_N = a.BASE_ID
				WHERE b.id = :uid";
				$batterys =  Yii::app()->db->createCommand($sql)->query(array(':uid' => Yii::app()->user->id));
								
				break;
			case 0:
				$bases = MtsysBase::model()->findAll();						
				$batterys =  BtBatterys::model()->findAll();
				
			default:
				break;
		}
		
		$this->render('create',array(
			'model'=>$model,
			'bases'=>$bases,
			'batterys'=>$batterys,				
		));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Sensors']))
		{
			$model->attributes=$_POST['Sensors'];
			if($model->save())
				$this->redirect(array('view','id'=>$model->RECORD_ID));
		}

		$this->render('update',array(
			'model'=>$model,
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		if(Yii::app()->request->isPostRequest)
		{
			// we only allow deletion via POST request
			$this->loadModel($id)->delete();

			// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
			if(!isset($_GET['ajax']))
				$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
		}
		else
			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		$dataProvider=new CActiveDataProvider('Sensors');
		$this->render('index',array(
			'dataProvider'=>$dataProvider,
		));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new Sensors('search');
		$setting = new Setting;
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Sensors']))
			$model->attributes=$_GET['Sensors'];

		$this->render('admin',array(
			'model'=>$model,
			'setting' => $setting,
		));
	}

	/*
	 * get serialport results here 
	 */
	public function actionResults()
	{
		$model = new Pickdata('search');
		$model->unsetAttributes();
		$this->layout = '//layouts/empty';
		$this->render('results',array(
				'model'=>$model,
		));
		
	}

	/*
	 * send command to serialport to pickup data
	*/
	public function actionCommand()
	{
		/* get user id*/
		$uid = Yii::app()->user->id;
		echo 'uid = '. $uid;
		
		/* serial port params*/
/*		$baud = 19200;
		$databits = 8;
		$stopbits = 0;
		$parity = 0; //0: none; 1: odd; 2: even
*/		
		$baud_array = array('19200','1200', '2400', '4800', 
'9600', '14400', '38400', '56000', '57600','1152000','128000','256000');
		
		$databits_array = array('8', '7', '6','5');
		$stopbits_array = array('1', '2');
		$parity_array = array('0', '1', '2');//array('NONE', 'ODD', 'EVEN');
 		
		if(isset($_POST['baud']) & isset($_POST['databits']) & isset($_POST['stopbits']) & isset($_POST['parity']) & isset($_POST['ids']))
		{
			$baud = $baud_array[$_POST['baud']];
			$databits = $databits_array[$_POST['databits']];
			$stopbits = $stopbits_array[$_POST['stopbits']];
			$parity = $parity_array[$_POST['parity']]; //0: none; 1: odd; 2: even
	
			$ids_str = $_POST['ids'];	
			$ids_array = preg_split("/[,]+/", $ids_str);	
			$num_ids = count($ids_array);
			$i = 0;
			foreach($ids_array as $ids_i){
				$ids[$i] = $ids_i;
				$i++;
			}	
		}
		else
		{
			exit();
		}		
		
		/*we put all params together and store in send buf */
		/*data protocol likes: 4 bytes data length  + data params
		 * len=34&uid=1&baud=19200&databits=8&stopbits=0&parity=0&num=5&id1=0&id2=1&id3=2&id4=3&id5=4
		 */
		$params_serial = '&uid='.$uid . '&baud='. $baud . '&databits='. $databits. '&stopbits=' . $stopbits . '&parity=' .$parity. '&num=' . $num_ids;  
		
		$params_ids = '';		
		for($i = 0; $i < $num_ids; $i++){
			$params_ids .= '&id' .$i .'=' .$ids[$i];
		}

		$params = $params_serial . $params_ids;		
		$len = strlen($params);
		
		$buf = '?len='. $len . $params;
		echo $buf . '\n';
		
		/*send all params to the server through socket*/
		
		$address = "127.0.0.1";
		$port = 8888;
		
		$header = '64';
		$fp = fsockopen($address,$port,$errno,$errstr,30);
				
		fwrite($fp, $buf);
/*
		$count = 5;
		while ($count > 0)
		{
			$count--;
			$len = strlen($buf);
			$ret = fwrite($fp, $len);
			if($ret > 0){
				echo 'send successfully\n';
				$response = fread($fp, 2);
				if(strncmp($response, 'ok', 2)){
					fwrite($fp, $buf);
					break;
				}else{
					//fix me if failed to write $len
				}	
			}			
			sleep(2);
		}
*/
		
		fclose($fp);
	}
	
	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($id)
	{
		$model=Sensors::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='sensors-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
}
